﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 仓库管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class WarehouseService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Warehouse> _warehouseRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public WarehouseService(SqlSugarRepository<Warehouse> warehouseRep, ISqlSugarClient sqlSugarClient)
    {
        _warehouseRep = warehouseRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询仓库管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询仓库管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<WarehouseOutput>> Page(PageWarehouseInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _warehouseRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.WarehouseCode.Contains(input.Keyword) || u.WarehouseName.Contains(input.Keyword) || u.Capacity.Contains(input.Keyword) || u.Addr.Contains(input.Keyword) || u.Remark.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WarehouseCode), u => u.WarehouseCode.Contains(input.WarehouseCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.WarehouseName), u => u.WarehouseName.Contains(input.WarehouseName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Capacity), u => u.Capacity.Contains(input.Capacity.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Addr), u => u.Addr.Contains(input.Addr.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(input.OrganizationID != null, u => u.OrganizationID == input.OrganizationID)
            .WhereIF(input.UserID != null, u => u.UserID == input.UserID)
            .WhereIF(input.Sort != null, u => u.Sort == input.Sort)
            .LeftJoin<Organization>((u, organization) => u.OrganizationID == organization.Id)
            .LeftJoin<UserManagement>((u, organization, user) => u.UserID == user.Id)
            .Select((u, organization, user) => new WarehouseOutput
            {
                Id = u.Id,
                WarehouseCode = u.WarehouseCode,
                WarehouseName = u.WarehouseName,
                Capacity = u.Capacity,
                Addr = u.Addr,
                OrganizationID = u.OrganizationID,
                OrganizationFkDisplayName = $"{organization.OrganizationName}",
                UserID = u.UserID,
                UserFkDisplayName = $"{user.UserName}",
                Sort = u.Sort,
                State = u.State,
                Lock = u.Lock,
                Remark = u.Remark,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取仓库管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取仓库管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Warehouse> Detail([FromQuery] QueryByIdWarehouseInput input)
    {
        return await _warehouseRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加仓库管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加仓库管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddWarehouseInput input)
    {
        var entity = input.Adapt<Warehouse>();
        return await _warehouseRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新仓库管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新仓库管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateWarehouseInput input)
    {
        var entity = input.Adapt<Warehouse>();
        await _warehouseRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除仓库管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除仓库管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteWarehouseInput input)
    {
        var entity = await _warehouseRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _warehouseRep.FakeDeleteAsync(entity);   //假删除
        //await _warehouseRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除仓库管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除仓库管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteWarehouseInput> input)
    {
        var exp = Expressionable.Create<Warehouse>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _warehouseRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _warehouseRep.FakeDeleteAsync(list);   //假删除
        //return await _warehouseRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataWarehouseInput input)
    {
        var organizationIDData = await _warehouseRep.Context.Queryable<Organization>()
            .InnerJoinIF<Warehouse>(input.FromPage, (u, r) => u.Id == r.OrganizationID)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.OrganizationName}"
            }).ToListAsync();
        var userIDData = await _warehouseRep.Context.Queryable<UserManagement>()
            .InnerJoinIF<Warehouse>(input.FromPage, (u, r) => u.Id == r.UserID)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.UserName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "organizationID", organizationIDData },
            { "userID", userIDData },
        };
    }
    
    /// <summary>
    /// 导出仓库管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出仓库管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageWarehouseInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportWarehouseOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "仓库管理导出记录");
    }
    
    /// <summary>
    /// 下载仓库管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载仓库管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportWarehouseOutput>(), "仓库管理导入模板", (_, info) =>
        {
            if (nameof(ExportWarehouseOutput.OrganizationFkDisplayName) == info.Name) return _warehouseRep.Context.Queryable<Organization>().Select(u => $"{u.OrganizationName}").Distinct().ToList();
            if (nameof(ExportWarehouseOutput.UserFkDisplayName) == info.Name) return _warehouseRep.Context.Queryable<UserManagement>().Select(u => $"{u.UserName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入仓库管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入仓库管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportWarehouseInput, Warehouse>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 组织ID
                    var organizationIDLabelList = pageItems.Where(x => x.OrganizationFkDisplayName != null).Select(x => x.OrganizationFkDisplayName).Distinct().ToList();
                    if (organizationIDLabelList.Any()) {
                        var organizationIDLinkMap = _warehouseRep.Context.Queryable<Organization>().Where(u => organizationIDLabelList.Contains($"{u.OrganizationName}")).ToList().ToDictionary(u => $"{u.OrganizationName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.OrganizationID = organizationIDLinkMap.GetValueOrDefault(e.OrganizationFkDisplayName ?? "");
                            if (e.OrganizationID == null) e.Error = "组织ID链接失败";
                        });
                    }
                    // 链接 用户ID
                    var userIDLabelList = pageItems.Where(x => x.UserFkDisplayName != null).Select(x => x.UserFkDisplayName).Distinct().ToList();
                    if (userIDLabelList.Any()) {
                        var userIDLinkMap = _warehouseRep.Context.Queryable<UserManagement>().Where(u => userIDLabelList.Contains($"{u.UserName}")).ToList().ToDictionary(u => $"{u.UserName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.UserID = userIDLinkMap.GetValueOrDefault(e.UserFkDisplayName ?? "");
                            if (e.UserID == null) e.Error = "用户ID链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Warehouse>>();
                    
                    var storageable = _warehouseRep.Context.Storageable(rows)
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.WarehouseCode), "仓库编号不能为空")
                        .SplitError(it => it.Item.WarehouseCode?.Length > 50, "仓库编号长度不能超过50个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.WarehouseName), "仓库名称不能为空")
                        .SplitError(it => it.Item.WarehouseName?.Length > 50, "仓库名称长度不能超过50个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Capacity), "仓库容量m³不能为空")
                        .SplitError(it => it.Item.Capacity?.Length > 32, "仓库容量m³长度不能超过32个字符")
                        .SplitError(it => string.IsNullOrWhiteSpace(it.Item.Addr), "仓库地址不能为空")
                        .SplitError(it => it.Item.Addr?.Length > 100, "仓库地址长度不能超过100个字符")
                        .SplitError(it => it.Item.Remark?.Length > 300, "备注长度不能超过300个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
